<template>
  <div class="personContailer">
    <div class="chatBox-info">
      <div class="chatBox-kuang chatBox-kuang-chat" ref="chatBoxkuang">
        <h2 class="chat-h">聊天</h2>
        <div class="chatBox-content-demo" data-comment="0" id="chatBox-content-chat">
        </div>
      </div>
      <div class="chatBox-kuang chatBox-kuang-question" ref="chatBoxkuang">
        <h2 class="chat-h">提问</h2>
        <div class="chatBox-content-demo" data-comment="1" id="chatBox-content-question">
        </div>
      </div>
    </div>

  </div>

</template>

<script>
  import {chatAPI} from '../api/index'
  import {Notification} from 'element-ui'
  import {videoAPI} from '../api/index'
  import urlUtil from '../assets/util/urlUtil'
  import {emotionList} from '../assets/common/emotionList'

  export default {
    name: 'person',
    data () {
      return {
        loginUser: {
          uid: this.$root.uid,
          username: this.$root.username,
          email: this.$root.email,
        },
        video: {
          liveNo: this.$route.query.liveNo == null ? urlUtil.getUrlKey('liveNo') : this.$route.query.liveNo
        },
        liveStatusEnum: {
          NotStart: 0,
          Starting: 1,
          End: 2,
          Back: 3
        },
        chatTypeEnum: {
          chat: 0,
          question: 1
        },
        heartCheck: {
          timeout: 55000, // 心跳时间
          serverTimeoutObj: null,
          timeoutObj: null,
          onclose_connected_count: 0,
          reset: this.reset,
          start: this.start
        },
        smallFaceSize: 77,
        topFaceIndex: [2, 3],
        versionTime :  new Date().getTime()
      }
    },
    components: {},
    created () {

    },
    mounted () {
      var _self = this
      // 加载文件详情
      _self.initVideoDetail()
        .then((res) => {
          _self.initWebSocket() // 初始化websockt 对象
          _self.initWsListener() // 初始化websocket 相关监听器
          _self.initChatData()
        }, (err) => {
          Notification.warning({
            title: '友情提示',
            message: err
          })
        })
    },
    destroyed () {
    },
    methods: {
      start () { // 前端ws重试机制，目前未采取
        var _self = this
        this.heartCheck.timeoutObj = setInterval(function () {
          // 不判断是否返回pong了，麻烦。。正常其实要返回pang的，才说明连接成功！
          if (_self.webSocket.readyState == 1) {
            console.log('连接状态，发送消息PING保持连接')
            var ping = {
              type: 'PING',
              videoId: _self.video.id,
              createUserCode: _self.loginUser.uid
            }
            _self.webSocket.send(JSON.stringify(ping))
          } else {
            _self.initWebSocket(false)
          }
        }, _self.heartCheck.timeout)
      },
      reset () {
        clearTimeout(this.heartCheck.timeoutObj)
        return this
      },
      initWebSocket () { // 初始化websocket连接
        var _self = this
        if (!window.WebSocket) {
          window.WebSocket = window.MozWebSocket
        }
        if (window.WebSocket) {
          this.webSocket = new WebSocket(process.env.NETTY_SERVER)
          this.webSocket.onmessage = function (event) {
            _self.heartCheck.reset().start()    // 如果获取到消息，说明连接是正常的，重置心跳检测
            var json = JSON.parse(event.data)
            if (json.status == 200) {
              var type = json.data.type
              switch (type) {
                case 'CONNECTED':
                  _self.ws.connectedReceive(json.data)
                  break
                case 'GROUP_SENDING':
                  _self.ws.groupReceive(json.data)
                  break
                case 'LIVE_SERVER':
                  _self.ws.liveServerReceive(json.data)
                  break
                case 'NOTICE': // 通知
                  _self.ws.noticeMessage(json.data)
                  break
                case 'PONG': // pong do nothing
                  console.log('收到消息PONG')
                  break
                default:
                  console.log('不正确的类型')
              }
            } else {
              alert(json.msg)
              console.log(json.msg)
            }
          }
          // 连接成功1秒后，将用户信息注册到服务器在线用户表
          this.webSocket.onopen = function () {
            _self.heartCheck.reset().start()
            setTimeout(function (event) {
              Notification.success({
                title: '友情提示',
                message: '聊天服务器连接成功！'
              })
              _self.ws.connected()

            }, 1000)
          }
          this.webSocket.onclose = function (event) {
            Notification.warning({
              title: '抱歉',
              message: '客户端失去连接...请刷新界面重新连接！'
            })
          }
          this.webSocket.onerror = function () {
            Notification.error({
              title: '抱歉',
              message: '聊天服务器无法连接！请联系管理员！'
            })
          }
        } else {
          Notification.warning({
            title: '抱歉',
            message: '您的浏览器不支持聊天服务, 请换用谷歌浏览器继续访问！'
          })
        }
      },
      initWsListener () { // 初始化wesocket监听对象
        var _self = this
        this.ws = {
          connected: function () {
            if (!window.WebSocket) {
              Notification.warning({
                title: '友情提示',
                message: '当前浏览器不支持！请换用谷歌浏览器继续浏览'
              })
              return
            }
            if (_self.webSocket.readyState == WebSocket.OPEN) {
              var data = {
                'userId': _self.loginUser.uid,
                'videoId': _self.video.id,
                'type': 'CONNECTED'
              }
              _self.webSocket.send(JSON.stringify(data))
            } else {
              Notification.warning({
                title: '友情提示',
                message: '聊天服务器没有开启！请刷新页面重试！'
              })
            }
          },
          connectedReceive: function (responseData) {
            _self.ctxId = responseData.ctxId
          },
          groupReceive: function (chat) {
            var chatStr
            if (chat.chatType == _self.chatTypeEnum.chat) { // 聊天
              chatStr = _self.buildContent(chat, chatStr, _self)
              $('#chatBox-content-chat').append(chatStr)
              _self.scrollToBottom(0)
            } else { // 提问
              chatStr = _self.buildContent(chat, chatStr, _self)
              $('#chatBox-content-question').append(chatStr)
              _self.scrollToBottom(1)
            }
          },
          liveServerReceive (data) {
            if (data.content == 'close') {
              Notification.warning({
                title: '友情提示',
                message: '当前直播已被关闭！'
              })
              _self.closeOrOpenLive('close', _self)
            } else {
              Notification.success({
                title: '友情提示',
                message: '直播开启！'
              })
              _self.closeOrOpenLive('open', _self)
            }
          },
          noticeMessage (data) {
            if (data.onlineUserNum) {
              _self.onlinePersonNum = data.onlineUserNum
            }
          },
          remove: function () {
            console.log('******************** 客户端被移除了 ***********************')
            _self.socketRemoveByMq()
          }
        }
      },
      initVideoDetail () {
        let _self = this
        return new Promise((resolve, reject) => {
          if (_self.video.liveNo == null) {
            Notification.error({
              title: '友情提示',
              message: '直播编号为空,无法正常加载视频！'
            })
            return
          }
          var params = {
            liveNo: _self.video.liveNo,
            uid: _self.loginUser.uid,
            username: _self.loginUser.username,
          }
          videoAPI.getVideoDetail(params, (res) => {
            if (res) {
              if (res.isShelves == 0) {
                reject('当前视频已下架！')
                return
              }
              if (res.isDeleted == 1) {
                reject('当前视频已被删除！')
                return
              }
              _self.video = res
              resolve('成功')
            } else {
              reject('当前视频不存在,可能视频配置错误,请联系平台管理员！')
            }
          })
        })
      },
      initChatData () { // 加载聊天提问
        let _self = this
        var params = {
          videoId: _self.video.id
        }
        chatAPI.getChatListOnPerson(params, (res) => {
          if (res) {
            if (res.chat) {
              setTimeout(() => {
                var data = res.chat
                var chatStr = ''
                for (let index in data) {
                  var chat = data[index] // 每个chat
                  chatStr += this.buildContent(chat, chatStr, _self)
                }
                $('#chatBox-content-chat').append(chatStr)
                _self.scrollToBottom(0)
              }, 100)
            }
            if (res.question) {
              var data = res.question
              var chatStr = ''
              for (let index in data) {
                var chat = data[index] // 每个chat
                chatStr += this.buildContent(chat, chatStr, _self)
              }
              $('#chatBox-content-question').append(chatStr)
              _self.scrollToBottom(1)
            }
          }
        })
      },
      scrollToBottom (type) {
        var idArr = ['#chatBox-content-chat', '#chatBox-content-question']
        $(idArr[type]).scrollTop($(idArr[type])[0].scrollHeight)
      },
      buildContent (chat, html, _self) {
        html = '<div class="row chat-row">' +
          '            <div class="col-sm-2  chat-content-person">' +
          '              <span class="person-avater">' + chat.createUserName.substring(1) + '</span>' +
          '            </div>' +
          '            <div class="col-sm-10">' +
          '              <div class="chat-person">' + chat.createUserName + '-' + chat.createUserCode + '</div>' +
          '              <div class=" chat-content">' + chat.content + '</div>' +
          '            </div>' +
          '          </div>'
        return _self.emotion(html)
      },
      // 将匹配结果替换表情图片
      emotion (res) { // 渲染表情
        var _self = this
        var str = ''
        let word = res.replace(/\#|\;/gi, '')
        const list = emotionList // 表情数组
        var arr = word.split('$')
        for (let i = 0; i < arr.length; i++) {
          let index = list.indexOf(arr[i])
          if (index !== -1) {
            if (index == 2) {
              str += `<img style="height: 120px;" src="https://img-oss.yunshanmeicai.com/infocube/emotion/${index}.gif?time=${_self.versionTime}" align="middle">`
            } else if (index > _self.smallFaceSize || _self.topFaceIndex.indexOf(index) != -1) {
              str += `<img style="width:120px;height: 120px;" src="https://img-oss.yunshanmeicai.com/infocube/emotion/${index}.gif?time=${_self.versionTime}" align="middle">`
            } else {
              str += `<img src="https://img-oss.yunshanmeicai.com/infocube/emotion/${index}.gif?time=${_self.versionTime}" align="middle">`
            }
          } else {
            str += arr[i]
          }
        }
        return str
      }
    },
    computed: {}

  }
</script>

<style>
  .chat-content-person {
    position: relative;
    top: 18px;
  }

  .person-avater {
    display: inline-block;
    width: 40px !important;
    height: 40px;
    border-radius: 50%;
    background: #eee;
    vertical-align: top;
    overflow: hidden;
    line-height: 48px;
    text-align: center;
    background: #1e9fff !important;
    color: #fff;
  }

  .chat-row {
    margin-bottom: 10px;
  }

  .chat-content {
    background: #8c85e6;
    color: #fff;
    text-align: left;
    min-height: 36px;
    max-width: 252px;
    text-align: left;
    padding: 4px 12px;
    border-radius: 6px;
    word-wrap: break-word;
    display: inline-block;
    position: relative;
  }

  .chat-content:before {
    position: absolute;
    content: "";
    top: 8px;
    left: -6px;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid #8c85e6;
  }


  .personContailer {
    position: static;
    background: url(../../static/images/personBack.png) no-repeat 50%;
    background-size: cover;
    min-height: 100vh;
    max-width: 100vw;
    padding-top: 40px;
    box-sizing: border-box;
    z-index: 0;
    margin-left: 0;
  }

  .chatBox-kuang {
    flex: 1;
    padding-left: 50px;
  }

  .chat-h {
    font-size: 30px;
    font-family: cursive;
  }

  .chatBox-info {
    background: transparent;
    padding: 30px 0;
    display: flex;
    margin: 0 200px;
    height: 100%;
    background: #F5F5F5;
    z-index: 999;
    position: relative;

  }

  .chatBox-kuang-question {
    border-left: 1px solid #D8D8D8;

  }

  .chatBox-content-demo {
    height: calc(100% - 95px);
    overflow-x: hidden;
    overflow-y: scroll;
  }

  .chatBox {
    width: calc(100vw - 120px);
    height: calc(100vh - 120px);
    display: block;
    position: relative;
    margin: 0 auto;
    z-index: 11;
    background-color: rgba(255, 255, 255, .9);

  }

  .chatBox-info,
  .chatBox-kuang {
    height: 100%;
    height: 90vh;
  }

  .chatBox-kuang-question .chat-message {
    font-size: 20px;
    line-height: 32px;
    color: #333333;;
  }

  .personContailer::before {
    position: absolute;
    content: '';
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;

  }
</style>
